package com.zzy.fileupload;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadSevlet
 */
public class UploadSevlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UploadSevlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();

		@SuppressWarnings("deprecation")
		String realPath = request.getRealPath("/upload");// 设置磁盘缓冲路径

		factory.setRepository(new File(realPath));
		
		factory.setSizeThreshold(1024 * 1024);// 设置创建缓冲大小

		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(-1);// 设置上传文件限制大小,-1无上限
		try {
			@SuppressWarnings("unchecked")
			List<FileItem> list = upload.parseRequest(request);
			String va = null;
			for (FileItem item : list) {
				String name = item.getFieldName();
				if (item.isFormField()) {// 判断是否是文件流
					va = item.getString("UTF-8");
					System.out.println(name + "=" + va);
				} else {
					String value = item.getName();// 会将完整路径名传过来

					int start = value.lastIndexOf("\\");

					String fileName = value.substring(start + 1);

					InputStream in = item.getInputStream();

					 item.write(new File(realPath,fileName)); //写入文件夹

					int index = fileName.lastIndexOf(".");

					String realFileName = fileName.substring(0, index);

					String type = fileName.substring(index + 1);

					// 自定义dao // 放入到数据库中
				//	UploadDomain dao = new UploadDomain();
				//	dao.insert(in, realFileName, type, va);

				}
			}
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
